package com.example.demo.service.impl;


import com.example.demo.domain.AjaxResult;
import com.example.demo.domain.KgFile;
import com.example.demo.mapper.KgFileMapper;
import com.example.demo.service.KgFileService;
import com.example.demo.utils.CosFileDownload;
import com.example.demo.utils.CosFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.net.URLDecoder; // 引入 URLDecoder
import java.nio.charset.StandardCharsets; // 引入 StandardCharsets

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 知识图谱后端接口 ServiceImpl
 * 接口的具体实现
 * @author wzh
 * @date 2025.4.16
 */

@Service
public class KgFileServiceImpl implements KgFileService {

    @Autowired
    private KgFileMapper kgFileMapper;

    @Autowired
    private CosFileUpload cosFileUpload;

    @Autowired
    private CosFileDownload cosFileDownload;

    @Override
    public AjaxResult upload(MultipartFile[] files) {
        return cosFileUpload.upload(files);
    }

    @Override
    public AjaxResult add(KgFile kgFile) {
        kgFileMapper.add(kgFile);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult getUrl(String filename) {
        String decodedFilename = filename;
        try {
            // 对文件名进行 URL 解码
            // 确保使用 UTF-8 编码，这是 URL 编码的常见标准
            decodedFilename = URLDecoder.decode(filename, StandardCharsets.UTF_8.name());

            // 打印日志，方便调试
            System.out.println("原始文件名 (Encoded): " + filename);
            System.out.println("解码后文件名 (Decoded): " + decodedFilename);

        } catch (Exception e) {
            // 如果解码失败（例如编码格式错误），则使用原始的 filename
            System.err.println("文件名 URL 解码失败，使用原始文件名: " + filename);
            e.printStackTrace();
        }

        return cosFileDownload.getUrl(decodedFilename);
    }

    @Override
    public List<KgFile> getById(Integer id) {
        return kgFileMapper.getById(id);
    }

    @Override
    public AjaxResult deleteById(Integer id) {
        kgFileMapper.deleteById(id);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult initialize(MultipartFile[] files) {
        try {
            // 保存上传的文件到临时目录
            String tempDir = "F:\\gitcode\\knowledgeGraph\\LightRAG\\uploads\\";
            File dir = new File(tempDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            List<String> tempFilePaths = new ArrayList<>();
            for (MultipartFile file : files) {
                String originalFilename = file.getOriginalFilename();
                String uniqueFileName = UUID.randomUUID() + "_" + originalFilename;
                File tempFile = new File(tempDir + uniqueFileName);
                file.transferTo(tempFile);
                tempFilePaths.add(tempFile.getAbsolutePath());
            }

            // 构建Python命令
            List<String> command = new ArrayList<>();
            command.add("python");
            command.add("F:\\gitcode\\knowledgeGraph\\LightRAG\\examples\\jsonTree.py");
            command.addAll(tempFilePaths);

            ProcessBuilder pb = new ProcessBuilder(command);
            pb.directory(new File("F:\\gitcode\\knowledgeGraph\\LightRAG\\examples").getParentFile());

            Process proc = pb.start();

            // 读取标准输出，此时python脚本返回的是处理好的节点信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder outputBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                outputBuilder.append(line);
            }

            // 读取标准错误输出
            BufferedReader err = new BufferedReader(new InputStreamReader(proc.getErrorStream(), StandardCharsets.UTF_8));
            while ((line = err.readLine()) != null) {
                System.err.println("Error: " + line);
            }

            int exitCode = proc.waitFor();

            if (exitCode != 0) {
                return AjaxResult.error("Python脚本执行失败，退出码：" + exitCode);
            }

            String jsonOutput = outputBuilder.toString();
            System.out.println("收到Python返回的JSON字符串：");
            System.out.println(jsonOutput);

            // 如果想，甚至可以直接返回给前端看
            return AjaxResult.success(jsonOutput);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("初始化失败：" + e.getMessage());
        }
    }

}
